﻿@model IEnumerable<SmallJob.Model.Banner>
@{
    ViewBag.Title = "ConfigBanner";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@if (ViewData["result"] != null)
{
    <div class="alert alert-success">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        Config Success
    </div>
}
<table class="table table-hover" id="table-configbanner">
    <thead>
        <tr>
            <th>Title</th>
            <th>Link</th>
            <th>Display Number</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr id="@item.ID">
                <td>@item.Title</td>
                <td>@item.Link</td>
                <td class="cell-displaynumber">
                    @item.DisplayNumber
                </td>
                <td>
                    @Html.ActionLink("Details", "Details", new { id = item.ID }, new { target = "_blank" })
                </td>
            </tr>
        }
    </tbody>
</table>
@using (Html.BeginForm("SaveConfigBanner", "Banner", FormMethod.Post, new { id = "form-configbanner" }))
{
    foreach (var item in Model)
    {
    <input type="hidden" class="hidden-inputdisplay-@item.ID" value="@item.DisplayNumber" name="banner-@item.ID" />
    }
    <input type="submit" value="Save Changes" class="btn" style="width: 120px;" />
    <input type="button" value="Reset" class="btn" style="width: 70px;" id="btn-reset" />
}

<script src="@Url.Content("~/Content/js/jquery.tablednd.js")"></script>
<script type="text/javascript">
    function reset() {
        var $table = $('#table-configbanner');
        var rows = $table.find('tr[id]').get();
        rows.sort(function (a, b) {
            var keyA = $(a).attr('id');
            var keyB = $(b).attr('id');
            console.log(keyA + '-' + keyB);
            if (keyA < keyB) return -1;
            if (keyA > keyB) return 1;
            return 0;
        });
        $.each(rows, function (index, row) {
            $table.children('tbody').append(row);
            $(row).find('.cell-displaynumber').text(index + 1);
            var id = row.id;
            $('.hidden-inputdisplay-' + id).val(index + 1);
        });

    }
    $(document).ready(function () {
        $('#table-configbanner').tableDnD({
            onDrop: function (table, row) {
                var rows = table.tBodies[0].rows;
                for (var i = 0; i < rows.length; i++) {
                    $(rows[i]).find('.cell-displaynumber').text(i + 1);
                    var id = rows[i].id;
                    $('.hidden-inputdisplay-' + id).val(i + 1);
                }
            }
        });
        $('#btn-reset').click(function () {
            reset();
        });
    });


    //each(function () {
    //    var id = $(this).id;
    //});
</script>
